<?php

namespace Controller;

use Lib\Controller\Controller,
    Lib\Request,
    Lib\Util\Util,
    Lib\Util\Session,
    Imagick,
    ImagickDraw,
    ImagickPixel;

class App extends Controller {

    public function __construct(Request $request) {
        parent::__construct($request);

        $this->loadMenu();
        $this->loadSettings();
        $this->loadBackground();
    }

    public function index() {
    }

    public function kontakt() {
        $this->title = 'Контакт';
        $Settings = (object)Session::read('Settings');

        if (! empty($Settings->kontakt_pozadina)) {
            $this->setBodyBackground($Settings->kontakt_pozadina);
        }

        $data = Request::post('data');
        if (! empty($data)) {

            $error = false;
            $to      = $Settings->email;
            $subject = 'Kontakt sa sajta: ' . $data->name;
            $message = $data->message;
            $headers = "From: no-reply@" . Request::server() . "\n".
                       "Reply-To: {$data->name}<{$data->email}>" . "\n";

            if ( empty($data->name) ||
                 empty($data->email) ||
                 empty($data->message) ||
                 empty($data->captcha)
                ) {

                $error = ERROR_ALL_FIELDS_REQUIRED;
                
            } elseif (! filter_var($data->email, FILTER_VALIDATE_EMAIL)) {
                $error = ERROR_INVALID_EMAIL;

            } elseif (strtolower($data->captcha) != Session::read('Kontakt.captcha')) {
                $error = ERROR_INVALID_CAPTCHA;

            } else if(! @mail($to, $subject, $message, $headers)) {
                $error = ERROR_UNKNOWN;
            }

            if ($error) {
                $this->set('data', (array)$data);
                Session::flash($error, 'error');
            } else {
                Session::flash(MESSAGE_SENT, 'ok');
                $this->redirect('/kontakt');
            }
        }
    }

    public function kontakt_captcha() {
        $buffer = "qwertyuiopasdfghjklzxcvbnm0123456789";
        $captcha = "";
        for ($i=0; $i<6; $i++) {
            $captcha .= substr($buffer, rand(0, strlen($buffer)-1), 1);
        }

        Session::write('Kontakt.captcha', $captcha);

        $background = new ImagickPixel('#eeeeee');
        $foreground  = new ImagickPixel('#777777');

        $img = new Imagick();
        $img->newImage(80, 24, $background);
        $img->setImageFormat('png');

        $draw = new ImagickDraw();
        $draw->setFillColor($foreground);
        $draw->setFont(DIR_PUBLIC . DS . "fonts" . DS . "RobotoCondensed.ttf");
        $draw->setFontSize(18);
        $draw->setFontWeight(800);
        $img->annotateImage($draw, 5, 20, 0, $captcha);

        header('Content-Type: image/png;filename=captcha.png');
        echo $img;

    }

    public function loadBackground() {
        $sessionKey = 'Background.image';
        $images = Session::read($sessionKey);
        if (empty($images)) {
            $images = self::bodyBackgrounds();
            Session::write($sessionKey, $images);
        }
        
        $idx = rand(0, count($images)-1);
        $img = $images[$idx];
        $this->setBodyBackground($img);
    }

    public function setBodyBackground($image) {
        $this->set('bodyBackground', $image);
    }

    public static function bodyBackgrounds() {
        $dirname    = DIR_IMG . DS . 'background';
        $images  = array();
        if ($dir = opendir($dirname)) {
            while($f = readdir($dir)) {
                $ext = strtolower(end(explode(".", $f)));
                if (in_array($ext, array("jpg","jpeg","bmp","png","gif"))) {
                    $images[] = $f;
                }
            }
        }

        return $images;
    }

    private function loadMenu() {
        $this->loadModel('Page');
        $pages = $this->Page->find();
        $activated = false;

        foreach ($pages as &$page) {
            $page['link'] = sprintf('/%d/%s', $page['id'], $page['title']);
            $page['active'] = Request::isActive($page['link']);
            $activated = $activated || $page['active'];
        }

        // kontakt page
        $kontaktActive = Request::isActive('/kontakt');
        $activated = $activated || $kontaktActive;
        $pages[] = array(
            'title' => 'Контакт',
            'link'  => '/kontakt',
            'active' => $kontaktActive
        );

        if (! $activated) {
            $pages[0]['active'] = true;
        }

        $this->set('menu', $pages);

    }

    private function loadSettings() {
        $this->loadModel('Setting');

        $settings = array();
        foreach($this->Setting->find() as $data) {
            $settings[$data['key']] = $data['value'];
        }

        Session::write('Settings', $settings);
        $this->set('settings', $settings);
    }

}